<?
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die();


if(!CModule::IncludeModule("iblock"))
{
    ShowError("Модуль Информационных блоков не установлен");
    return;
}

if (!$USER->IsAuthorized())
{
    ShowError("Вы должны авторизоваться, чтобы иметь возможность создавать заявки.");
    return;        
}

if (!(CSite::InGroup(array($arParams["GROUP_CLIENTS"])) || CSite::InGroup(array($arParams["GROUP_ADMINS"])) || CSite::InGroup(array($arParams["GROUP_PERFORMERS"]))))
{
    ShowError("У Вас нет доступа к заявкам. Обратитесь в отдел ИТО для предоставления Вам доступа.");
    return;        
}
    
if(!isset($arParams["CACHE_TIME"]))
	$arParams["CACHE_TIME"] = 3600;

$arParams["IBLOCK_TYPE"] = trim($arParams["IBLOCK_TYPE"]);
if(strlen($arParams["IBLOCK_TYPE"])<=0)
 	$arParams["IBLOCK_TYPE"] = "itrequests";
if($arParams["IBLOCK_TYPE"]=="-")
	$arParams["IBLOCK_TYPE"] = "";


$uid = $USER->GetID();
$isAdmin = CSite::InGroup(array($arParams["GROUP_ADMINS"]));
$isPerformer = CSite::InGroup(array($arParams["GROUP_PERFORMERS"]));
$isClient = CSite::InGroup(array($arParams["GROUP_CLIENTS"]));


// **************** фильтр ***********************
$FILTER_NAME = $arParams["MAIL_TEMPL_PREFIX"]."_FILTER";
$arFilterFields = Array("find","find_type","find_lamp","find_close","find_category_id","find_project_id","find_status_id","find_my_only","find_to_wiki_id");

if (($isAdmin || $isPerformer) && (strlen($_REQUEST["set_filter"])<=0) && (strlen($_REQUEST["del_filter"])<=0) && ($_SESSION["SESS_ADMIN"][$FILTER_NAME."_USING"]!=true))
{
    $_REQUEST["set_filter"] = 1;
    $_REQUEST["find_lamp"] = array("red", "yellow");
    if ($arParams["SHARED_LIST"])
        $_REQUEST["find_my_only"] = "on";
}

// Работа с фильтрами
//Delete filter
if (strlen($_REQUEST["del_filter"])>0)
{
    unset($_SESSION["SESS_ADMIN"][$FILTER_NAME]);

    foreach ($arFilterFields as $field)
        $_REQUEST[$field] = "";
}
//Set filter
elseif (strlen($_REQUEST["set_filter"])>0)
{
    $arFilter = Array();
    foreach ($arFilterFields as $field)
        $arFilter[$field] = $_REQUEST[$field];

    $_SESSION["SESS_ADMIN"][$FILTER_NAME] = $arFilter;
    $_SESSION["SESS_ADMIN"][$FILTER_NAME."_USING"] = true;
}
//Get Filter
else
{
    $arFilter = $_SESSION["SESS_ADMIN"][$FILTER_NAME];
    if (is_array($arFilter))
    {
        foreach ($arFilter as $field => $value)
            $_REQUEST[$field] = $value;
    }
}

$find = $_REQUEST["find"];
$find_type = $_REQUEST["find_type"];
$find_lamp = $_REQUEST["find_lamp"];
$find_close = $_REQUEST["find_close"];
$find_category_id = $_REQUEST["find_category_id"];
$find_project_id = $_REQUEST["find_project_id"];
$find_status_id = $_REQUEST["find_status_id"];
$find_my_only = $_REQUEST["find_my_only"];
$find_to_wiki_id = $_REQUEST["find_to_wiki_id"];

// ***************************************

if($this->StartResultCache(false, array($uid,$FILTER_NAME,$find,$find_type,$find_lamp,$find_close,$find_category_id, $find_status_id,$find_my_only,$find_to_wiki_id)))
{   

    $arResult=array(
        "HANDBOOKS" => array(),
        "REQUESTS" => array(),
        "ISADMIN" => $isAdmin,
        "ISPERFORMER" => $isPerformer,
        "SECTION" => $APPLICATION->GetCurPage(),        
        "FILTER_NAME" => $FILTER_NAME,
        "FILTER_FIND" => $find,
        "FILTER_FIND_TYPE" => $find_type,
        "FILTER_FIND_LAMP" => $find_lamp,
        "FILTER_FIND_CLOSE" => $find_close,
        "FILTER_FIND_CATEGORY_ID" => $find_category_id,
        "FILTER_FIND_PROJECT_ID" => $find_project_id,
        "FILTER_FIND_STATUS_ID" => $find_status_id,
        "FILTER_FIND_MY_ONLY" => $find_my_only,
        "FILTER_FIND_TO_WIKI_ID" => $find_to_wiki_id
    );

    // категории
    $arSelect = Array(
        "ID",
        "NAME",
        "PROPERTY_DEFAULT_RESPONSIBLE"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CATEGORY"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");
        
    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["CATEGORY"][] = $arItem;            
    }        

    if ($arParams["USE_PROJECT"]=="Y")
    {
        // проекты
        $arSelect = Array(
            "ID",
            "NAME"
        );

        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_PROJECT"],
            "ACTIVE" => "Y",
        );
        $arSort = array("SORT"=>"ASC");

        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
        while($arItem = $rsElement->GetNext())
        {
            $arResult["HANDBOOKS"]["PROJECT"][] = $arItem;            
        }       
    }
    
    // статусы
    $arSelect = Array(
        "ID",
        "NAME"
    );

    $arFilter = array(
        "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
        "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_STATUSES"],
        "ACTIVE" => "Y",
    );
    $arSort = array("SORT"=>"ASC");
        
    $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);
    while($arItem = $rsElement->GetNext())
    {
        $arResult["HANDBOOKS"]["STATUSES"][] = $arItem;            
    }       
    
    // варианты добавления в базу знаний
    $property_enums = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$arParams["IBLOCK_REQUESTS_ID"], "CODE"=>"TO_WIKI"));
    while($enum_fields = $property_enums->GetNext())
    {
        $arResult["HANDBOOKS"]["TO_WIKI"][] = $enum_fields;
    }

    
    
    // выбираем свойства инфоблока для определения типа комментария
    $types = array();
    $prs = CIBlockPropertyEnum::GetList(Array("DEF"=>"DESC", "SORT"=>"ASC"), Array("IBLOCK_ID"=>$arParams["IBLOCK_REQUESTS_LOGS_ID"], "CODE"=>"TYPE"));
    while($field = $prs->GetNext())
    {
        $types[$field["VALUE"]] = $field["ID"];
    }                
    

    $arSelect = array(
        "ID",
        "NAME",
        "CREATED_BY",
        "DETAIL_PAGE_URL",
        "PROPERTY_STATUS",
        "PROPERTY_CATEGORY",
        "PROPERTY_RESPONSIBLE_USER",
        "PROPERTY_CRITICALITY",
        "PROPERTY_DATE_CLOSE"
    );

    if ($isAdmin || $isPerformer || ($arParams["SHARE_LIST"]=="Y"))
    {
        $arFilter = array (
                "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_ID"],
                "ACTIVE" => "Y",
        );
    }
    else 
    {
        $arFilter = array (
                "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_ID"],
                "ACTIVE" => "Y",
                "CREATED_BY" => $USER->GetID(),
        );
    }
    
    $arOrder = array(
            "DATE_CREATE"=>"DESC",
    );

//    if ($USER->GetID()=="1")
    {
        if (strlen($find))
        {
            if ($find_type=="id")
                $arFilter["ID"] = $find;
            else
            if ($find_type=="name")
                $arFilter["NAME"] = "%".$find."%";
        }

        
        if ($find_close=="N")
            $arFilter["PROPERTY_DATE_CLOSE"] = false;
        else
        if ($find_close=="Y")
            $arFilter[">PROPERTY_DATE_CLOSE"] = "0";

        
        if ($find_category_id=="0")
            $arFilter["PROPERTY_CATEGORY"] = false;
        else
        if ($find_category_id)
            $arFilter["PROPERTY_CATEGORY"] = $find_category_id;

        if ($arParams["USE_PROJECT"]=="Y")
        {
            if ($find_project_id=="0")
                $arFilter["PROPERTY_PROJECT"] = false;
            else
            if ($find_project_id)
                $arFilter["PROPERTY_PROJECT"] = $find_project_id;
        }        
        
        if ($find_status_id=="0")
            $arFilter["PROPERTY_STATUS"] = false;
        else
        if ($find_status_id)
            $arFilter["PROPERTY_STATUS"] = $find_status_id;
        
        if ($find_my_only)
            $arFilter["CREATED_BY"] = $uid;
//        else
//            $arFilter["CREATED_BY"] = false;
        
        if ($find_to_wiki_id=="0")
            $arFilter["PROPERTY_TO_WIKI"] = false;
        else
        if ($find_to_wiki_id)
            $arFilter["PROPERTY_TO_WIKI"] = $find_to_wiki_id;
        
    }
    
    $rsItems = CIBlockElement::GetList($arOrder, $arFilter, false, false, $arSelect);

    while ($item = $rsItems->GetNext())
    {
        $rsUser = CUser::GetByID($item["PROPERTY_RESPONSIBLE_USER_VALUE"]);
        if ($arUser = $rsUser->Fetch())
            $item["RESPONSIBLE_USER"] = $arUser["NAME"]." ".$arUser["LAST_NAME"];
        
        $rsUser = CUser::GetByID($item["CREATED_BY"]);
        if ($arUser = $rsUser->Fetch())
            $item["CREATED_BY"] = $arUser["NAME"]." ".$arUser["LAST_NAME"]; 
        
        // критичность
        $arFilter = array(
            "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
            "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CRITICALITY"],
            "ID" => $item["PROPERTY_CRITICALITY_VALUE"],
            "ACTIVE" => "Y",
        );
        $rsElement = CIBlockElement::GetList(array("SORT"=>"ASC"), $arFilter, false, array("nTopCount"=>"1"), array("ID", "NAME"));
        if ($elem = $rsElement->GetNext())
            $item["CRITICALITY"] = $elem["NAME"];
        
        // статус
        if ($item["PROPERTY_STATUS_VALUE"])
        {
            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_STATUSES"],
                "ID" => $item["PROPERTY_STATUS_VALUE"],
                "ACTIVE" => "Y",
            );
            $rsElement = CIBlockElement::GetList(array("SORT"=>"ASC"), $arFilter, false, array("nTopCount"=>"1"), array("ID", "NAME"));
            if ($elem = $rsElement->GetNext())
                $item["STATUS"] = $elem["NAME"];
        }
        
        // категория
        if ($item["PROPERTY_CATEGORY_VALUE"])
        {
            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_HANDBOOKS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_HANDBOOKS_CATEGORY"],
                "ID" => $item["PROPERTY_CATEGORY_VALUE"],
                "ACTIVE" => "Y",
            );
            $rsElement = CIBlockElement::GetList(array("SORT"=>"ASC"), $arFilter, false, array("nTopCount"=>"1"), array("ID", "NAME"));
            if ($elem = $rsElement->GetNext())
                $item["CATEGORY"] = $elem["NAME"];
        }
                
        // дата ответа и кол-во сообщений
        $arSelect = Array(
            "ID",
            "DATE_CREATE",
            "CREATED_BY",
            "PREVIEW_TEXT"
        );

        if ($isAdmin || $isPerformer)
        {
            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_LOGS_ID"],
                "ACTIVE" => "Y",
                "PROPERTY_REQUEST" => $item["ID"],
                "!PROPERTY_TYPE" => array($types["Системная"])
            );
        }
        else
        {
            $arFilter = array(
                "IBLOCK_TYPE" => $arParams["IBLOCK_REQUESTS_TYPE"],
                "IBLOCK_ID"=> $arParams["IBLOCK_REQUESTS_LOGS_ID"],
                "ACTIVE" => "Y",
                "PROPERTY_REQUEST" => $item["ID"],
                "!PROPERTY_TYPE" => array($types["Системная"], $types["Комментарий скрытый"])
            );            
        }

        $arSort = array("DATE_CREATE"=>"ASC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);        
        $item["CNT_LOGS"] = $rsElement->SelectedRowsCount();        
        if ($elem = $rsElement->GetNext())
        {
            $item["PREVIEW_TEXT"] = $elem["PREVIEW_TEXT"];
        }       
        
        $arSort = array("DATE_CREATE"=>"DESC");
        
        $rsElement = CIBlockElement::GetList($arSort, $arFilter, false, false, $arSelect);        
        $item["CNT_LOGS"] = $rsElement->SelectedRowsCount();        
        if ($elem = $rsElement->GetNext())
        {
            $item["LAST_DATE"] = $elem["DATE_CREATE"];
        }       
        
        // индикатор определяем по последнему оставленному сообщению в обсуждении
        if ($elem["ID"])
        {
            if (strlen($item["PROPERTY_DATE_CLOSE_VALUE"]))
            {
                $item["INDICATOR"] = "<div class='lamp-grey'></div>";
                $item["INDICATOR_FILTER"] = "grey";
            }
            else
            if ($uid == $elem["CREATED_BY"])
            {
                $item["INDICATOR"] = "<div class='lamp-green'></div>";
                $item["INDICATOR_FILTER"] = "green";
            }
            else                
            if (($arParams["SHARE_LIST"]=="Y") && $isClient && (in_array($arParams["GROUP_PERFORMERS"], CUser::GetUserGroup($elem["CREATED_BY"])) || in_array($arParams["GROUP_ADMINS"], CUser::GetUserGroup($elem["CREATED_BY"]))))
            {
                $item["INDICATOR"] = "<div class='lamp-red'></div>";
                $item["INDICATOR_FILTER"] = "red";
            }
            else
            if (in_array($arParams["GROUP_PERFORMERS"], CUser::GetUserGroup($elem["CREATED_BY"])) || in_array($arParams["GROUP_ADMINS"], CUser::GetUserGroup($elem["CREATED_BY"])))
            {
                $item["INDICATOR"] = "<div class='lamp-green-s'></div>";
                $item["INDICATOR_FILTER"] = "green_s";
            }
            else
            if ($item["PROPERTY_RESPONSIBLE_USER_VALUE"] == $uid)
            {
                $item["INDICATOR"] = "<div class='lamp-red'></div>";
                $item["INDICATOR_FILTER"] = "red";
            }
            else
            {
                $item["INDICATOR"] = "<div class='lamp-yellow'></div>";
                $item["INDICATOR_FILTER"] = "yellow";
            }
        }
        else 
        {
            if (strlen($item["PROPERTY_DATE_CLOSE_VALUE"]))
            {
                $item["INDICATOR"] = "<div class='lamp-grey'></div>";
                $item["INDICATOR_FILTER"] = "grey";
            }
            else
            {
                $item["INDICATOR"] = "<div class='lamp-green'></div>";
                $item["INDICATOR_FILTER"] = "green";
            }
        }
        
        
        $res_lamp = $res_owner = $res_message = true;
        if (is_array($find_lamp))
        {
            if (!in_array($item["INDICATOR_FILTER"], $find_lamp))
                $res_lamp = false;
        }
        if (strlen($find) && $find_type=="owner")
        {
            if (strpos(mb_strtolower($item["CREATED_BY"], "utf-8"), mb_strtolower($find, "utf-8"))===false)
                $res_owner = false;
        }
        if (strlen($find) && $find_type=="message")
        {
            if (strpos(mb_strtolower($item["PREVIEW_TEXT"], "utf-8"), mb_strtolower($find, "utf-8"))===false)
                $res_message = false;
        }
        
        if ($res_lamp && $res_owner && $res_message)
            $arResult["REQUESTS"][] = $item;
    }
    
   
    $this->IncludeComponentTemplate();
}
?>


